package woaini.wind.bot.chat.config;

import com.coze.openapi.service.auth.JWTOAuth;
import com.coze.openapi.service.auth.JWTOAuthClient;
import com.coze.openapi.service.service.CozeAPI;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import woaini.wind.bot.core.exception.BotAssertTool;
import woaini.wind.bot.core.exception.enums.BotExceptionType;

@Configuration
@EnableConfigurationProperties(CozeChatterConfig.class)
@RequiredArgsConstructor
@Slf4j
public class CozeAutoConfig {

  private final CozeChatterConfig config;

  @Bean
  public CozeAPI cozeAPI() {
    JWTOAuthClient oauth = null;
    try {
      oauth =
          new JWTOAuthClient.JWTOAuthBuilder()
              .clientID(config.getClientId())
              .privateKey(config.getPrivateKey())
              .publicKey(config.getPublicKeyId())
              .baseURL(config.getCozeApiBase())
              .build();
    } catch (Exception e) {
      log.error("coze chat error", e);
      BotAssertTool.isActualTrue(
          true, BotExceptionType.BOT_RPC_PARAMS, "异常:\r\n{}", e.getMessage());
    }

    // 初始化api信息
    return new CozeAPI.Builder()
        .baseURL(config.getCozeApiBase())
        .auth(new JWTOAuth(oauth))
        .readTimeout(10000)
        .build();
  }
}
